import MD5 from 'crypto-js/md5';
import HmacSHA256 from 'crypto-js/hmac-sha256';
import http from './http';
import { Body } from "@tauri-apps/api/http";
import { useBiliStore } from '@/stores/bili';
import { message } from '@/utils/message';

const baseUrl='https://live-open.biliapi.com';

function getEncodeHeader(params = {}){
  const key=import.meta.env.VITE_BILI_KEY;
  const secert=import.meta.env.VITE_BILI_SECRET;
  const timestamp = parseInt(Date.now() / 1000 + "");
  const nonce = parseInt(Math.random() * 100000 + "") + timestamp;
  //hex：95c0ded762c2559ff87d2547045df2aa
  //base64: lcDe12LCVZ/4fSVHBF3yqg==
  //toString: 95c0ded762c2559ff87d2547045df2aa
  const header:any = {
      "x-bili-accesskeyid": key,
      "x-bili-content-md5": MD5(JSON.stringify(params)).toString(),
      "x-bili-signature-method": "HMAC-SHA256",
      "x-bili-signature-nonce": nonce + "",
      "x-bili-signature-version": "1.0",
      "x-bili-timestamp": timestamp+""
  }
  const data: string[] = []
  for (const key in header) {
      data.push(`${key}:${header[key]}`)
  }
  const signature = HmacSHA256(data.join('\n'),secert).toString();
  return {
      Accept: "application/json",
      "Content-Type": "application/json",
      ...header,
      Authorization: signature
  }
}
export function startApp(){
  const biliStore=useBiliStore();
  const appId=import.meta.env.VITE_BILI_APP_ID;
  if(!biliStore.code) return Promise.reject('参数错误');
  const params={
    code:biliStore.code,
    app_id:parseInt(appId)
  }
  return http.post(`${baseUrl}/v2/app/start`,Body.text(JSON.stringify(params)),{
    headers:getEncodeHeader(params)
  }).then((res:any) =>{
    if(res.code==0){
      biliStore.gameId=res.data?.game_info?.game_id ??'';
      biliStore.uid=res.data?.anchor_info?.uid;
      biliStore.uname=res.data?.anchor_info?.uname;
      biliStore.uface=res.data?.anchor_info?.uface;
      biliStore.roomId=res.data?.anchor_info?.room_id;
      biliStore.wssLinks=res.data?.websocket_info?.wss_link;
      biliStore.authBody=res.data?.websocket_info?.auth_body;
      heartBeat();
    }else{
      message('error',res.message);
      return Promise.reject(res);
    }
  })
}
export function endApp(){
  const biliStore=useBiliStore();
  const appId=import.meta.env.VITE_BILI_APP_ID;
  const params={
    game_id:biliStore.gameId,
    app_id:parseInt(appId)
  }
  return http.post(`${baseUrl}/v2/app/end`,Body.text(JSON.stringify(params)),{
    headers:getEncodeHeader(params)
  }).then((res:any) =>{
    if(res.code==0){

    }
  })
}
export function heartBeat(){
  const biliStore=useBiliStore();
  if(!biliStore.gameId) return Promise.reject('参数错误');
  const params={
    game_id:biliStore.gameId
  }
  return http.post(`${baseUrl}/v2/app/heartbeat`,Body.text(JSON.stringify(params)),{
    headers:getEncodeHeader(params)
  }).then((res:any) =>{
    if(res.code==0){
      setTimeout(heartBeat,50*1000);
    }
  })
}